<template>
  <div class="contract-container">
    <el-card class="contract-header">
      <!-- 搜索表单 -->
      <el-form :model="searchForm" :inline="true" label-width="80px" class="basic-search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keywords"
            placeholder="请输入合同编号/名称/客户"
            clearable
            @keyup.enter="handleSearch"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item>
          <div class="search-buttons">
            <div class="left-buttons">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="contract-content">
      <div class="table-header">
        <h3 class="table-title">作废合同</h3>
      </div>

      <!-- 数据表格 - 替换为 Element Plus 的原生表格组件 -->
      <el-table
        v-loading="loading"
        :data="contractList"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        max-height="600"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="code" label="合同编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="name" label="合同名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="customer" label="客户名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="cate_name" label="合同类别" width="100" show-overflow-tooltip />
        <el-table-column label="合同状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '有效' : '作废' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="合同金额" width="100" align="right">
          <template #default="{ row }">
            <span class="amount-cell">{{ formatCurrency(row.cost) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sign_time_formatted" label="签约时间" width="110" align="center" />
        <el-table-column prop="void_time_formatted" label="作废时间" width="110" align="center" />
        <el-table-column prop="void_user" label="作废人" width="100" show-overflow-tooltip />
        <el-table-column label="操作" width="240" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="warning" @click="handleUnvoid(row)">取消作废</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 - 替换为 Element Plus 的原生分页组件 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryForm.page"
          v-model:page-size="queryForm.limit"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 合同详情抽屉 -->
    <GlobalDrawer
      v-model="detailDrawerVisible"
      title="合同详情"
      size="80%"
      :show-footer-buttons="false"
    >
      <div class="drawer-content">
        <SaleContractView
          :contract-id="currentDetailContractId"
          :key="'contract-view-' + currentDetailContractId"
        />
      </div>
    </GlobalDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { formatCurrency } from '@/utils/format'
  import { useRouter } from 'vue-router'
  import { contractApi } from '@/api/contract'
  import type { Contract } from '@/types/contract'
  import { GlobalDrawer } from '@/components/common'
  import SaleContractView from './SaleContractView.vue'

  // 路由
  const router = useRouter()

  // 搜索表单
  const searchForm = reactive({
    keywords: '',
  })

  // 查询参数
  const queryForm = reactive({
    page: 1,
    limit: 10,
  })

  // 数据列表相关
  const contractList = ref<Contract[]>([])
  const total = ref(0)
  const loading = ref(false)

  // 抽屉相关
  const detailDrawerVisible = ref(false)
  const currentDetailContractId = ref('')

  // 格式化时间戳为日期（秒级时间戳）
  const formatDate = (timestamp: number | string | undefined) => {
    if (!timestamp || timestamp === 0) return ''
    const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
    const date = new Date(ts * 1000) // 将秒级时间戳转换为毫秒级
    return date.toISOString().split('T')[0] // 返回 YYYY-MM-DD 格式
  }

  // 处理搜索
  const handleSearch = () => {
    queryForm.page = 1
    getContractList()
  }

  // 处理重置
  const handleReset = () => {
    searchForm.keywords = ''
    queryForm.page = 1
    getContractList()
  }

  // 处理查看
  const handleView = (row: Contract) => {
    // 先关闭再打开抽屉，确保每次点击都会触发重新加载
    detailDrawerVisible.value = false
    // 使用setTimeout确保关闭动画完成后再打开
    setTimeout(() => {
      currentDetailContractId.value = row.id.toString()
      detailDrawerVisible.value = true
    }, 300)
  }

  // 处理取消作废
  const handleUnvoid = (row: Contract) => {
    ElMessageBox.confirm(`确定要取消作废合同【${row.name}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const response: any = await contractApi.contractVoid({
            id: row.id,
            status: 0,
            void_remark: '用户手动取消作废',
          })

          if (response.code === 0) {
            ElMessage.success('取消作废成功')
            getContractList()
          } else {
            ElMessage.error(response.msg || '取消作废失败')
          }
        } catch (error) {
          ElMessage.error('取消作废失败')
        }
      })
      .catch(() => {
        // 用户取消操作
      })
  }

  // 处理分页大小变化
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    getContractList()
  }

  // 处理当前页变化
  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    getContractList()
  }

  // 获取合同列表
  const getContractList = async () => {
    try {
      loading.value = true

      // 构造查询参数
      const params = {
        ...queryForm,
        ...searchForm,
        void_status: 1,
      }

      // 调用后端接口
      const response: any = await contractApi.getVoidList(params)

      if (response.code === 0) {
        if (Array.isArray(response.data.list)) {
          // 处理数据，格式化时间字段
          contractList.value = response.data.list.map((item: any) => {
            return {
              ...item,
              sign_time_formatted: formatDate(item.sign_time),
              void_time_formatted: formatDate(item.void_time),
            } as Contract
          })
          total.value = response.data.count || 0
        } else {
          contractList.value = []
          total.value = 0
        }
      } else {
        ElMessage.error(response.msg || '获取作废合同列表失败')
        contractList.value = []
        total.value = 0
      }
    } catch (error) {
      ElMessage.error('获取作废合同列表失败')
      contractList.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 初始化数据
  onMounted(() => {
    getContractList()
  })
</script>

<style scoped>
  .contract-container {
    padding: 0;
  }

  .contract-header {
    margin-bottom: 16px;
  }

  .contract-content {
    margin-bottom: 16px;
  }

  .search-buttons {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .table-title {
    font-size: 18px;
    font-weight: 500;
    margin: 0;
  }

  .amount-cell {
    font-weight: bold;
    color: #67c23a;
  }
</style>
